package com.jfinal.demo.web.render;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.jfinal.demo.config.common.Constants;
import com.jfinal.render.FileRender;
import com.jfinal.render.RenderException;
import com.jfinal.render.RenderFactory;

/**
 * 图片展示render
 * 
 * @author Administrator
 * 
 */
public class ImageFileRender extends FileRender {

	private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";

	private File file;

	public ImageFileRender(File file) {
		super(file);
		this.file = file;
	}

	public void render() {
		if (file == null || !file.isFile()) {
			RenderFactory.me().getErrorRender(404)
					.setContext(request, response).render();
			return;
		}

		String fileName = file.getName().toLowerCase();
		String surfix = fileName.substring(fileName.lastIndexOf(".") + 1);
		String contentType = Constants.IMAGE_MIME_TYPES.get(surfix);
		response.setContentType(contentType != null ? contentType
				: DEFAULT_CONTENT_TYPE);

		normalRender();
	}

	private void normalRender() {
		response.setHeader("Content-Length", String.valueOf(file.length()));
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = new BufferedInputStream(new FileInputStream(file));
			outputStream = response.getOutputStream();
			byte[] buffer = new byte[1024];
			for (int len = -1; (len = inputStream.read(buffer)) != -1;) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush();
		} catch (IOException e) {
			if (getDevMode())
				throw new RenderException(e);
		} catch (Exception e) {
			throw new RenderException(e);
		} finally {
			if (inputStream != null)
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			if (outputStream != null)
				try {
					outputStream.close();
				} catch (IOException e) {
				}
		}
	}
}
